const db = require("../db")
var date = require("silly-datetime");
const path = require("path")
const fs = require('fs')
var brandId = null;
function getId(id) {
    // console.log(id);
   brandId = id
}
module.exports = {
    // 获取商品列表
    getGoods: (req, res) => {
        const param = req.body
        let end = param.limit
        let start = (param.page - 1) * end

        let sql = 'select goods.*,brand.brandName as brand,shop.shopName from goods,brand,shop where 1 =1 and goods.brand = brand.id and goods.shopId = shop.id'
        let arr = []
        if (param.goodName != "" && param.goodName != undefined) {
            let goodName = '%' + param.goodName + '%';
            sql += ' and goodName like ?'
            arr.push(goodName)
        }
        if (param.brand != null && param.brand != "") {
            sql += ' and brand = ?'
            arr.push(param.brand)
        }
        sql += ' and is_delete = 0 order by createTime desc limit ?,? ;select count(*) as total from goods'
        arr.push(start, parseInt(end))
        db.query(sql, arr, function (err, result) {
            if (err) return res.cc(err)
            return res.send({
                code: 200,
                msg: '获取商品列表成功！',
                count: result[1][0].total,
                data: [...result[0]]
            })
        })
    },
    // 新增商品
    addGoods: async (req, res) => {
        const goodsInfo = req.body
        goodsInfo['is_delete'] = 0
        goodsInfo.putInTime = date.format(goodsInfo.putInTime)
        var today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); // 2019-01-01
        db.query("select id from brand where brandName = ?", goodsInfo['brand'], async (err, result) => {
            if (err) return res.cc(err)
            if (result.length == 0) {
                db.query("insert into brand set ? ;select id from brand where brandName = ?", [{
                    'brandName': goodsInfo['brand']
                }, goodsInfo['brand']], async (err, result) => {
                    if (err) return res.cc(err)
                    goodsInfo['brand'] = result[1][0].id;
                    goodsInfo['createTime'] = today
                    db.query("insert into goods set ?", goodsInfo, function (err, result) {
                        if (err) return res.cc(err)
                        if (result.affectedRows != 1) return res.cc("新增商品失败！", -1)
                        return res.cc("新增商品成功！", 200)
                    })
                })
            } else {
                db.query("select id from brand where brandName = ?", goodsInfo['brand'], async (err, result) => {
                    if (err) return res.cc("添加品牌失败")
                    goodsInfo['brand'] = result[0].id;
                    goodsInfo['createTime'] = today
                    db.query("insert into goods set ?", goodsInfo, function (err, result) {
                        if (err) return res.cc(err)
                        if (result.affectedRows != 1) return res.cc("新增商品失败！", -1)
                        return res.cc("新增商品成功！", 200)
                    })
                })
            }
    
        })
       
    },
    // 删除商品
    delGoods: (req, res) => {
        const id = req.body.id
        db.query("update goods set is_delete = 1 where id = ?", id, function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows != 1) return res.cc("删除商品失败，请稍后重试！", -1)
            return res.cc("删除商品成功！", 200)
        })
    },
    // 根据id查询商品详情
    findGoods: (req, res) => {
        const id = req.body.id
        db.query("select goods.id ,goodName,category,unit,brand.brandName as brand,number,fileId,shop.shopName,shop.id as shopId,putInTime,price,model,shopLocation,resource,shoplng,shoplat from goods,brand,shop where is_delete = 0 and goods.id= ? and brand.id = goods.brand and goods.shopId = shop.id limit 1 ", id, function (err, result) {

            if (err) return res.cc(err)
            if (result.length != 1) return res.cc("查询商品详情失败！", -1)
            let data = result[0]
            data['url'] = []
            if (result[0].fileId != null && result[0].fileId != '') {
                // let files = result[0].fileId.split(",")
                db.query(`select picName from goods_pic where id in (${result[0].fileId})`, function (err, result) {
                    if (err) return res.cc(err)
                    data['url'] = [...result]
                    return res.send({
                        code: 200,
                        msg: '获取商品详情成功！',
                        data: data
                    })

                })

            } else {
                return res.send({
                    code: 200,
                    msg: "查询成功！",
                    data: data
                })
            }


        })
    },
    // 修改商品
    updateGoods: (req, res) => {
        const newInfo = req.body
		 newInfo.putInTime = date.format(newInfo.putInTime)
        let str = `update goods inner join (select brand.id as id from brand where brandName = '${newInfo.brand}' ) c set goods.brand = c.id, ? where goods.id = ${newInfo['id']} `

        // let arr ={}

        var now = date.format(new Date(), 'YYYY-MM-DD hh:mm:ss');

        // if(newInfo.goodName != null && newInfo.goodName != ''){
        //     // str += ' goodName =?,'
        //     arr['goodName'] = newInfo.goodName
        // } 
        // if(newInfo.unit != null && newInfo.unit != ''){
        //     // str += 'unit = ?,'
        //     arr['unit'] = newInfo.unit
        // }
        // if(newInfo.category != null && newInfo.category != ''){
        //     // str += ' category=?,'
        //     arr['category'] = newInfo.category
        // }
        // str += ``
        delete newInfo['brand']
        delete newInfo['id']
        delete newInfo['url']
        newInfo['updateTime'] = now
        // arr['id'] = newInfo.id
        db.query(str, newInfo, function (err, result) {
            if (err) return res.cc(err)

            if (result.affectedRows != 1) return res.cc("更新商品信息失败！", -1)
            return res.cc("更新商品信息成功", 200)
        })

    },
    // 获取所有品牌
    getBrand: (req, res) => {
        db.query("select * from brand", function (err, result) {
            if (err) return res.cc(err)
            return res.send({
                code: 200,
                msg: '获取品牌列表成功！',
                data: [...result]
            })
        })
    },
    // 添加品牌
    insertBrand: (req, res) => {
        const brandInfo = req.body
        db.query("insert into brand set ?", brandInfo, function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("添加品牌信息失败", -1)
            return res.cc("添加品牌信息成功", 200)
        })

    },
    // 分页获取所有品牌
    getBrandByPage:(req,res)=>{
        let queryInfo = req.body
        let sql = `select * from brand limit ${parseInt((queryInfo.page-1)*queryInfo.limit)},${queryInfo.page*queryInfo.limit}`
        db.query(sql,function(err,result){
            if(err) return res.cc(err)
            res.send({
                code:200,
                msg:"获取品牌列表成功！",
                data:[...result]
            })
        })
    },
    // 上传图片
    uploadImg: (req, res) => {

        var filePath = './' + req.files[0].path;
        // 文件类型
        var temp = req.files[0].originalname.split('.');
        var fileType = temp[temp.length - 1];
        var lastName = '.' + fileType;
        // 构建图片名
        var fileName = Date.now() + lastName;
        // 图片重命名
        fs.rename(filePath, './images/' + fileName, async (err) => {
            if (err) {
                return ''
            } else {
                var localFile = './images/' + fileName;
                var key = fileName
                let param = {
                    'pic_url': localFile,
                    'picName': key
                }
                let str = `insert into goods_pic  set ?`
                let str2 = `select id,picName from goods_pic order by id desc limit  1`
                db.query(str, param, function (err, result) {
                    if (err) return res.cc(err)
                    if (result.affectedRows !== 1) return res.cc("上传图片失败")
                    db.query(str2, function (err, result) {
                        if (err) return res.cc(err)
                        return res.send({
                            code: 200,
                            msg: "上传图片成功",
                            data: {
                                id: result[0].id,
                                url: result[0].picName
                            }
                        })
                    })
                })
            }
        });
    },
    // 获取所有店铺
    getShop:(req,res)=>{
        db.query("select * from shop",function(err,result){
            if(err) return res.cc(err)
            return res.send({
                code:200,
                msg:"获取店铺列表成功！",
                data:result
            })
        })
    },
    // 根据条件获取店铺
    getShopList:(req,res)=>{
        let queryInfo = req.body
        let sql = `select * from shop limit ${parseInt((queryInfo.page-1)*queryInfo.limit)},${queryInfo.page*queryInfo.limit}`
        console.log(sql);
        db.query(sql,function(err,result){
            if(err) return res.cc(err)
            res.send({
                code:200,
                msg:"获取店铺列表成功！",
                data:[...result]
            })
        })
    }

}